using System;
using System.ComponentModel;

namespace Library.WebControls {

	/// <summary>
	/// Control support ajax technology
	/// </summary>
	public class BaseAjaxControl : BaseControl {
		protected BaseAjaxControl() {
		}

		protected const char Fail = 'F';
		protected const char Success = 'S';




		protected static readonly Type CoreAjaxType = typeof(BaseAjaxControl);
		/// <summary>
		/// Get is control callback
		/// </summary>
		[Browsable(false)]
		public virtual bool IsCallback {
			get {
				return false;
			}
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			if (IsLibraryWebControlsCallback)
				return;
			if (!Page.ClientScript.IsClientScriptBlockRegistered(CoreAjaxType, "BaseURL")) {
				Page.ClientScript.RegisterClientScriptBlock(CoreAjaxType, "BaseURL", String.Format("var _spglobalRequestUrl = '{0}';", Page.Request.Url.AbsoluteUri), true);
			}
			if (!Page.ClientScript.IsClientScriptIncludeRegistered(CoreAjaxType, "CoreJsAjax")) {
				Page.ClientScript.RegisterClientScriptInclude(CoreAjaxType, "CoreJsAjax", Page.ClientScript.GetWebResourceUrl(CoreAjaxType, "Library.WebControls.CoreJs.AjaxCore.js"));
			}
		}
		/// <summary>
		/// Get parameter pass from client
		/// </summary>
		/// <param name="parameter">Parameter key</param>
		/// <returns></returns>
		public string GetClientQueryValue(string parameter) {
			if (Request != null) {
				return Request[parameter];
			}
			return null;
		}

		protected void ClearAllResponseContain() {
			Response.Clear();
			Response.ClearHeaders();
		}

		private string _customCallbackResult;
		protected void ProcessCustomCallbackEventArgs(CustomCallbackEventArgs e) {
			_customCallbackResult = e.Result;//Context.Server.HtmlEncode(e.Result);
		}

		protected void WriteCustomCallbackCompleteResult() {
			Page.Response.Clear();
			Page.Response.ClearContent();
			Page.Response.ClearHeaders();
			Page.Response.Write(Success);
			if (!String.IsNullOrEmpty(_customCallbackResult)) {
				Page.Response.Write(_customCallbackResult.Length);
				Page.Response.Write("|");
				Page.Response.Write(_customCallbackResult);
			} else {
				Page.Response.Write("0|");
			}
		}


		protected void FlushAndEndCallback() {
			Response.Flush();
			try {
				Page.Response.End();
				// ReSharper disable EmptyGeneralCatchClause
			} catch {
				// ReSharper restore EmptyGeneralCatchClause
			}
		}



		protected void WriteError(Exception ex) {
			string message;
			var basePage = Page as BasePage;
			if (basePage != null) {
				bool handled;
				basePage.OnSimpleCallbackThrowException(this, ex, out handled, out message);
				if (handled) return;
			} else {
				message = String.Format("{0}: {1}", ex.GetType().FullName, ex.Message);
			}
			Response.ClearContent();
			Response.Write(Fail);
			Response.Write(message);
			Response.Flush();
			Response.End();
		}
	}
}
